import request from '../service/api'
import Taro from "@tarojs/taro";

export default {
  namespace: 'invoice',
  state: {
    orderList: [],
    selectedOrders: [],
    current: 0,
  },
  effects: {
    * init(_, {put}) {
      yield put({
        type: 'getOrderList'
      });
      // yield put({
      //   type: 'getInvoiceList'
      // })
    },
    // 第一步:查询可开发票的订单.
    * getOrderList({payload}, {call, put, select}) {
      const {phoneNumberInStore} = yield select(({app}) => app)
      const {
        statusCode,
        data: {data, code} = {},
      } = yield call(() => request.post('/invoice/findOrderOfInvoice', {
        userPhone: phoneNumberInStore,
        payType: 1
      }));
      console.log('发票信息', data);
      if (statusCode === 200 && code === 200) {
        yield put({
          type: 'setState',
          payload: {
            orderList: data && data.length ? data.filter((i) => !i.flag) : [],
            orderList2: data && data.length ? data.filter((i) => i.flag === 1) : [],
            selectedOrders: [],
          }
        })
      }
    },
    // 查询已申请的发票数据
    *getInvoiceList(_, {call, put}){
      const data = yield call(() => request.get('/invoice/list'));
      console.log('查询已申请的发票数据', data);
    },
    // 第二步:查询订单合并后的发票数
    * initStep2(_, {call, select, put}) {
      const {selectedOrders = []} = yield select(({invoice}) => invoice);
      console.log('selectedOrders', selectedOrders);
      const orderIds = selectedOrders.map((i) => i.orderId);
      const {
        statusCode,
        data: {data, code} = {},
      } = yield call(() => request.post('/invoice/mergeInvoiceOfTenant', [...orderIds]));
      console.log('initStep2', data);
      if (statusCode === 200 && code === 200) {
        yield put({
          type: 'setState',
          payload: {
            mergeList: data,
          }
        })
      }
    },
    // 第三步:申请开票
    *applyInvoice({payload}, {call, put, select}){
      const {selectedOrders = []} = yield select(({invoice}) => invoice);
      console.log('payload', payload);
      console.log('selectedOrders', selectedOrders);
      const orderIds = selectedOrders.map((i) => i.orderId) || [];
      console.log('orderIds', orderIds);
      const {data = {}} = yield call(() => request.post('/invoice/createInvoiceOfTenant', {...payload, orderIdList: [...orderIds]}));
      console.log('data', data);
      if (data && data.code === 200){
        Taro.showToast({
          title: '申请成功,请耐心等待运营商开票',
          icon: 'none'
        });
        Taro.reLaunch({url: '/pages/mine/index'})
      }
    }
  },
  reducers: {
    setState(state, {payload}) {
      return {
        ...state,
        ...payload
      }
    }
  }
}
